#include <stdio.h>
#include <string.h> /* memset */
#include <stdlib.h> /* malloc */

#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>


#include <netinet/ip.h>

#include "dump_packet.h"

int sock_raw;

void process_packet(unsigned char *buff, int size)
{
    struct iphdr *iph = (struct iphdr *) buff;

    switch (iph->protocol)
    {
        case IPPROTO_ICMP:
	    dump_icmp_packet(buff, size);
	    break;
        case IPPROTO_TCP:
	    dump_tcp_packet(buff, size);
            break;
        case IPPROTO_UDP:
	    dump_udp_packet(buff, size);
            break;
	default:
	  break;  
    }



}

int main(int argc, char **argv)
{
   
    struct sockaddr saddr;
    struct in_addr in;
    int saddr_size,data_size;

    sock_raw = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
    if ( sock_raw < 0)
    {
        printf("Socket Error\n");
	return 1;
    }

    unsigned char *buffer = (unsigned char *) malloc (65536);

    set_log_stdout();
    while (1)
    {
        saddr_size = sizeof saddr;
	data_size = recvfrom(sock_raw, buffer, 65535, 0, &saddr, &saddr_size);
	if ( data_size < 0) {
            printf("Recvfrom error, failed to get packets\n");
	    return 1;
	}

	// process the packet
        process_packet(buffer, data_size );	

    }
 
    return 0;
}
